<template>
  <ul class="list-scroll-ul"
      v-infinite-scroll="load">
    <li v-for="(item,index) in compSourceData"
        :key="index"
        class="list-scroll-li">
      <slot :index="index" :item="item" :key="index" name="list-item"></slot>
    </li>
    <li class="list-scroll-li-loading" v-if="loadMore">
      <slot name="loadMore" v-if="$refs.loadMore"></slot>
      <div v-else>加载更多...</div>
    </li>
    <li class="list-scroll-li-loading" v-else-if="noLoadData">
      <slot name="noLoadData" v-if="$refs.noLoadData"></slot>
      <div v-else> 没有更多数据....</div>
    </li>
  </ul>
</template>

<script lang="ts" setup>
// @ts-ignore
import {getCurrentInstance, ref} from "vue";

defineOptions({
  name: "ListView"
});

const props = defineProps({
      action: {
        type: String, default: ""
      },
      height: {
        type: String, default: "400px"
      },
      params: {
        type: Object, default: function () {
          return {}
        }
      },
      pageSize: {
        type: Number, default: 10
      }
    }
);
//加载的数据
const compSourceData = ref<any>([]);
//加载更多
const loadMore = ref<Boolean>(false);
//没有更多
const noLoadData = ref<Boolean>(false);
//总页数
const total = ref(0);
//当前页码
const currentPageNum = ref(0);

// @ts-ignore
let {proxy} = getCurrentInstance()

const load = () => {
  if (currentPageNum.value === 0 || total.value === 0) {
    compSourceData.value = [];
  } else if (compSourceData.value.length >= total.value) {
    noLoadData.value = true;
  }
  if (!loadMore.value && !noLoadData.value) {
    currentPageNum.value = (currentPageNum.value + 1);
    //加载更多
    loadMore.value = true;
    //禁用没有更多
    noLoadData.value = false;
    getData();
  }
}

const getData = () => {
  const formData: any = {};
  formData.pageSize = props.pageSize;
  formData.pageNo = currentPageNum.value;
  Object.keys(props.params).forEach((key) => {
    formData[key] = props.params[key];
  });
  proxy.$http.post(props.action, formData).then((apiData: any) => {
    console.log(apiData);
    total.value = apiData.data.total;
    compSourceData.value.push(...apiData.data['rows']);
    loadMore.value = false;
  });
}

</script>

<style scoped>
.list-scroll-ul {
  width: 100%;
  list-style: none;
  height: v-bind(height);
  overflow-y: auto;
}

.list-scroll-ul :deep(li) {
  width: 100%;
  list-style: none;
}

.list-scroll-ul .list-scroll-li, .list-scroll-ul .list-scroll-li-loading {
  width: 100%;
  text-align: left;
  line-height: 20px;
  list-style: none;
}

.list-scroll-ul .list-scroll-li-loading {
  text-align: center;
  line-height: 25px;
}
</style>